<?php

namespace App\Http\Controllers\Api;

use App\Models\Product;
use App\Models\Category;
use Illuminate\Http\Request;

class ProductsController extends ApiController
{
    /**
     *
     * @return mixed
     */
    public function index()
    {
        $products = Product::where('on_sale',1)->get();
        $product_recommend = Array();
        $product_new = Array();
        $product_hot = Array();
        foreach($products as $product)
        {
            unset($product->description);
            unset($product->carousel_image);
            $p = $product->toArray();
            $p['colors'] = $product->color_info->toArray();
            if($product->is_hot)
            {
                $product_hot[] = $p;
            }
            if($product->is_recommend)
            {
                $product_recommend[] = $p;
            }
            if($product->is_new)
            {
                $product_new[] = $p;
            }
        }
        $data['products'] = $products;
        $data['h_products'] = $product_hot;
        $data['r_products'] = $product_recommend;
        $data['n_products'] = $product_new;
        return $this->success($data);
    }

    public function getProductsBycategory(Request $request)
    {
        if(!$request->category){
            return $this->success('请输入分类','error');
        }
        $category = Category::find($request->category);
        if(empty($category))
        {
            return $this->success('分类不存在','error');
        }
        $products = Product::where(['on_sale'=>1,'category_id'=>$request->category])->get();
        $productArr = Array();
        foreach($products as $product)
        {
            unset($product->description);
            unset($product->carousel_image);
            $p = $product->toArray();
            $p['colors'] = $product->color_info->toArray();
            $productArr[] = $p;
        }
        $data['products'] = $productArr;
        $data['category_name'] = $category->name;
        return $this->success($data);
    }

    public function detail(Product $product)
    {
        if(empty($product))
        {
            return $this->success('商品不存在','error');
        }
        else{
            if($product->on_sale == 0)
            {
                return $this->success('商品已下架','error');
            }
            $carousel_images = Array();
            foreach($product->carousel_image as $img)
            {
                $carousel_images[] = $product->getImageUrl($img);
            }
            unset($product->carousel_image);
            $product->carousel_images=$carousel_images;
            $product->colors=$product->color_info;
            $data['product'] = $product;
            return $this->success($data);
        }
    }

}
